package ktvdownloadserver

import (
	"fmt"
	"ktvserver/core/session"
	"ktvserver/core/tcpserver"
	"ktvserver/ktvutil"
	//"log"
)

var serverList = make(map[int]*tcpserver.Server, 2)

//////////////////////////////////////////////////////////////////////////////////
// 协议定义

//////////////////////////////////////////////////////////////////////////////////

// 启动服务
func StartServer() {

	// 测试服务器
	//go StartServerByPort(9006)

	StartServerByPort(ktvutil.GetDownloadServerPort())

}

// 停止服务
func StopServer() {

	// 关闭TCP连接
	for port, server := range serverList {
		server.Kill()
		delete(serverList, port)
	}

}

func StartServerByPort(port int) {
	// 注册处理函数协议
	myMux := GetServerMux()

	// 开始监听指定的端口
	server := &tcpserver.Server{
		Addr:            fmt.Sprintf(":%d", port),
		Handler:         myMux,
		SpeedReportFunc: MySpeedReportFunc}

	// 根据端口来记录服务器
	serverList[port] = server

	server.ListenAndServe()
}

// 处理函数示例
func handleExample(w tcpserver.ResponseWriter, req *tcpserver.Request) {
	fmt.Println("handlefile")

}

// 速度报告函数
func MySpeedReportFunc(remoteAddr string, token uint64, recvBytes int64, sentbytes int64) {
	session.SetDownloadingSpeed(token, recvBytes, sentbytes)
	//log.Printf("SpeedReport, remoteAddr=%s, token=%x, bytes=%d", remoteAddr, token, sentbytes)
}

// 获取已经发送的流量
func GetSentBytes() int64 {

	var sum int64
	for _, server := range serverList {
		sum += server.WrittenBytes
	}

	return sum
}

// 获取已经接收的字节数
func GetRecvBytes() int64 {
	var sum int64
	for _, server := range serverList {
		sum += server.ReadedBytes
	}

	return sum
}
